package org.wannatrak.android.helper;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;

/**
 * @Author: Maksim Tulupov maxtulupov@gmail.com
 * @Date: $Date: 2011-06-14 13:32:03 +0000 (Tue, 14 Jun 2011) $ 4:06:15 PM
 * @version: $Revision: 2 $
 * @id: $Id: DatabaseHelper.java 2 2011-06-14 13:32:03Z maxtulupov@gmail.com $
 */
public class DatabaseHelper {
    
    private SQLiteOpenHelper openHelper;

    public DatabaseHelper(SQLiteOpenHelper openHelper) {
        this.openHelper = openHelper;
    }
    
    public void createTransaction(boolean readOnly) {
        SQLiteDatabase sqLiteDatabase = readOnly ? openHelper.getReadableDatabase() : openHelper.getWritableDatabase();
            sqLiteDatabase.beginTransaction();
    }

    public void createTransaction() {
        createTransaction(false);
    }

    public void markTransactionAsSuccess() {
        openHelper.getWritableDatabase().setTransactionSuccessful();
    }

    public void endTransaction() {
        openHelper.getWritableDatabase().endTransaction();
    }

    public boolean inTransaction() {
        return openHelper.getWritableDatabase().inTransaction();
    }

    public void closeDb() {
        SQLiteDatabase writableDatabase = openHelper.getWritableDatabase();
        if (writableDatabase.isOpen()) {
            writableDatabase.close();
        }
    }

    public void executeSQL(String sql, Object[] params) {
        SQLiteDatabase writableDatabase = openHelper.getWritableDatabase();
        writableDatabase.execSQL(sql, params);
    }

    public Cursor executeRawSQL(String sql, String[] params) {
        SQLiteDatabase writableDatabase = openHelper.getWritableDatabase();
        return writableDatabase.rawQuery(sql, params);
    }

    public Cursor executeRawSQL(SQLiteQueryBuilder builder, String[] projection, String selection, 
                                String[] selectionArgs, String groupBy, String having, String sortOrder, String limit) {
        SQLiteDatabase writableDatabase = openHelper.getWritableDatabase();
        if (limit == null) {
            return builder.query(writableDatabase, projection, selection,  selectionArgs, groupBy, having, sortOrder);
        } else {
            return builder.query(writableDatabase, projection, selection,  selectionArgs, groupBy, having, sortOrder, limit);
        }
    }
}
